package com.bkhech.netty.websocket;

import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * ClientChannelGroup
 *  用于记录和管理所有客户端的 channel 组
 *
 *  知识点：
 *    1. ChannelGroup 是 Netty 提供的，用于管理 Channel 的集合，ChannelGroup.writeAndFlush("hello") 方法，可向已注册的所有 channel 发送消息，相当于 broadcast 的意思，
 *
 * @author guowm
 * @date 2024-11-11
 */
public class ClientChannelGroup {
    private static volatile ChannelGroup clients;

    private ClientChannelGroup() {
    }

    public static ChannelGroup getInstance() {
//        clients.writeAndFlush("hello");
        if (clients == null) {
            synchronized (ClientChannelGroup.class) {
                if (clients == null) {
                    clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
                }
            }
        }
        return clients;
    }


    /*private ChannelGroupSingleton() {
    }

    public static ChannelGroup getInstance(){
        return Singleton.HOLDER.clients;
    }

    private enum Singleton {
        HOLDER;
        private final ChannelGroup clients;

        Singleton() {
            clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
        }
    }*/
}
